/* eslint-disable @typescript-eslint/no-unused-vars */
import React, { useState, useEffect, useMemo, useCallback, useRef } from 'react';
import './index.scss';
import { Table, Button, Select, Form, DatePicker, Tooltip, Space, Empty } from 'antd';
const { Option } = Select;
const { RangePicker } = DatePicker;
import {
  flownodejumpout,
  callresult,
  hotspotquestion,
  datastatistics,
  taskscanceldatapermission,
  robotscanceldatapermission,
} from 'seats/servers/servers';
import { Line } from '@ant-design/charts';
import { clearNull } from 'utils/tools';
import moment from 'moment';

import { QuestionCircleFilled, VerticalAlignBottomOutlined } from '@ant-design/icons';
import { JSONObject } from '../../schema/common';
import {
  FetchDataParam,
  FetchDataResponse,
  PageSelect,
} from '../../../components/UILibrary/pageSelect';

import ExcelJS from 'exceljs';
// @ts-ignore
import saveAs from 'file-saver';

// 隐藏的节点
const hiddenItems = ['呼损率', '意向客户数', '意向客户比例'];
// 隐藏的呼叫结果统计
const hiddenStatus = [
  '关机',
  '空号',
  '停机',
  '正在通话中',
  '暂停服务',
  '拨号方式不正确',
  '呼入限制',
  '来电提醒',
  '呼叫转移失败',
  '网络忙',
  '欠费',
  '无法接听',
  '改号',
  '线路故障',
  '稍后再拨',
  '呼损',
  '黑名单用户',
  '呼叫频次限制',
  '处理中',
];

const HomePage: React.FC = () => {
  /**时间选择器-格式定义 */
  const dateFormat = 'YYYY-MM-DD';
  /**图表加载状态 */
  const [chartLoading, setChartLoading] = useState(false);
  /**form Ref */
  const [form] = Form.useForm();
  /**任务列表组件Ref */
  const sSelectRef1 = useRef<any>();
  /**机器人列表组件Ref */
  const sSelectRef2 = useRef<any>();

  /**当前页 */
  const [currentPage, setCurrentPage] = useState(1);

  const initCallData = {
    callNumberTotal: 0,
    connectCountTotal: 0,
    connectRateTotal: 0,
    callLossRateTotal: 0,
    totalTalkTimeTotal: 0,
    aveTalkTimeTotal: 0,
    userIntentionNumberTotal: 0,
    userIntentionRateTotal: 0,
  };
  const [callData, setCallData] = useState<any>(initCallData); // 数据统计区块-line数据，包含总数
  const [flownodejumpoutList, setFlownodejumpoutList] = useState<any>({
    list: [],
    total: 1,
  }); // 话术跳出率列表
  const [jumpLoading, setJumpLoading] = useState(false);
  const [hotspotquestionList, setHotspotquestionList] = useState<any>([]); // 热门问题
  const [callresultList, setcallresultList] = useState<any>([]); // 呼叫结果统计
  const [callresultTotal, setcallresultTotal] = useState<any>(0); // 呼叫总数
  const [chartData, setChartData] = useState<any>([]); // 呼叫统计区块-line数据，数组[]

  const [timeType, setTimeType] = useState(1); // 时间类型
  const [isZDYdate, setIsZDYdate] = useState(false); // 是否位自定义时间模式
  const today = moment().format(dateFormat); // 今天

  /**查询参数初始数据 */
  const initSearchRefValue = {
    flowType: '',
    taskId: '',
    robotId: '',
    beginTime: today,
    endTime: today,
  };
  /**存储查询条件 */
  const searchRef = useRef<any>(initSearchRefValue);

  const [flowType, setFlowType] = useState(''); // 任务类型
  const [taskId, setTaskId] = useState(''); // 任务id (注意: 机器Id与任务Id只能传其中一个参数)
  const [robotId, setRobotId] = useState(''); // 机器人Id (注意: 机器Id与任务Id只能传其中一个参数)
  const [beginTime, setBeginTime] = useState(today); // 开始时间
  const [endTime, setEndTime] = useState(today); // 结束时间

  /**时间范围选择 */
  function onDateChange(value: any, dateString: any) {
    const [beginTime, endTime] = dateString;
    setBeginTime(beginTime);
    setEndTime(endTime);
    setItemQry({
      beginTime,
      endTime,
    });
  }
  /**是否为整数 */
  function isInteger(obj: number) {
    return Math.floor(obj) === obj;
  }
  /**数字保留1位小数 */
  function forMateToFixed2(number: number) {
    return number.toFixed(1);
  }
  /**转为位百分比 29.3% */
  function forMateToRato(number: number) {
    if (!number) return '0';
    return Number((number * 100).toFixed(1)) + '%';
  }

  /**支持自定义模板-自定义tooltip提示框 */
  function customTooltip(title: string, items: any[]) {
    return (
      <>
        <div style={{ marginTop: 10 }}>时间：{title}</div>
        <ul style={{ paddingLeft: 0 }}>
          {items?.map((item: { data?: any }, index: any) => {
            const {
              data: { name, value, valShow },
            } = item;
            return (
              <li key={index} className="g2-tooltip-list-item" data-index={index}>
                <span>{name}：</span>
                <span className="g2-tooltip-list-item-value">{valShow ? valShow : value}</span>
              </li>
            );
          })}
        </ul>
      </>
    );
  }

  /**数据统计Line的config配置 */
  const common_config = useMemo(() => {
    const config = {
      padding: [5, 0],
      height: 120,
      data: [],
      xField: 'time',
      yField: 'value',
      xAxis: {
        label: false,
        tickCount: 24,
        // grid: {
        //   line: {
        //     style: {
        //       stroke: 'rgba(0,0,0,0.05)',
        //       // lineDash: [4, 4],
        //     },
        //   },
        //   alternateColor: 'rgb(245, 245, 245)',
        // },
      },
      yAxis: false,
      lineStyle: {
        stroke: 'l(0) 0:#66d2fa 1:#a478ee',
      },
      tooltip: {},
      smooth: true,
      animation: {
        appear: {
          animation: 'path-in',
          duration: 1500,
        },
      },
    };
    return config;
  }, []);

  /**呼叫量*/
  const callNumberConfig = useMemo(() => {
    const tooltip = {
      customContent: customTooltip,
    };
    return {
      ...common_config,
      data: callData.callNumber || [],
      tooltip,
    };
  }, [callData.callNumber, common_config]);

  /**接通数*/
  const connectCountConfig = useMemo(() => {
    const tooltip = {
      customContent: customTooltip,
    };
    return {
      ...common_config,
      data: callData.connectCount || [],
      tooltip,
    };
  }, [callData.connectCount, common_config]);

  /**接通率*/
  const connectRateConfig = useMemo(() => {
    const list = callData.connectRate || [];
    const tooltip = {
      customContent: customTooltip,
    };
    return {
      ...common_config,
      data: list,
      tooltip,
    };
  }, [callData.connectRate, common_config]);

  /**呼损率*/
  const callLossRateConfig = useMemo(() => {
    const list = callData.callLossRate || [];
    const tooltip = {
      customContent: customTooltip,
    };
    return {
      ...common_config,
      data: list,
      tooltip,
    };
  }, [callData.callLossRate, common_config]);

  /**总通话时长*/
  const totalTalkTimeConfig = useMemo(() => {
    const tooltip = {
      customContent: customTooltip,
    };
    return { ...common_config, data: callData.totalTalkTime || [], tooltip };
  }, [callData.totalTalkTime, common_config]);

  /**平均通话时长*/
  const aveTalkTimeConfig = useMemo(() => {
    const tooltip = {
      customContent: customTooltip,
    };
    return { ...common_config, data: callData.aveTalkTime || [], tooltip };
  }, [callData.aveTalkTime, common_config]);

  /**意向客户数*/
  const userIntentionNumberConfig = useMemo(() => {
    const tooltip = {
      customContent: customTooltip,
    };
    return {
      ...common_config,
      data: callData.userIntentionNumber || [],
      tooltip,
    };
  }, [callData.userIntentionNumber, common_config]);

  /**意向客户比例*/
  const userIntentionRateConfig = useMemo(() => {
    const list = callData.userIntentionRate || [];
    const tooltip = {
      customContent: customTooltip,
    };
    return {
      ...common_config,
      data: list,
      tooltip,
    };
  }, [callData.userIntentionRate, common_config]);

  /**呼叫统计折线配置config*/
  const getLineConfig = useMemo(() => {
    // chart数据格式定义
    const tooltip = {
      customContent: customTooltip,
    };
    const config = {
      data: chartData,
      xField: 'time',
      yField: 'value',
      seriesField: 'name',
      meta: {},
      tooltip,
      xAxis: { tickCount: 12 },
      yAxis: {
        label: {
          formatter: function formatter(v: any) {
            return isInteger(Number(v)) ? v : '';
          },
        },
      },
      smooth: true,
      animation: {
        appear: {
          animation: 'path-in',
          duration: 1000,
        },
      },
    };
    return config;
  }, [chartData]);

  /**点击切换时间类型*/
  const handleSizeChange = (type: any) => {
    setTimeType(type);
    const today = moment().format(dateFormat);
    let start = '';
    let end = '';
    if (type === 1) {
      start = today;
      end = today;
    } else if (type === 2) {
      const day = moment().add(-1, 'days').format(dateFormat);
      start = day;
      end = day;
    } else if (type === 3) {
      start = moment().weekday(0).format(dateFormat); //本周一
      end = moment().weekday(6).format(dateFormat); //本周日
    } else if (type === 4) {
      const day = moment().format(dateFormat);
      start = moment(day).startOf('month').format(dateFormat); //本周一
      end = moment(day).endOf('month').format(dateFormat); //本周日
    } else if (type === 0) {
    }
    console.log(start, end);
    if (!start || !end) {
      return;
    }
    setBeginTime(start);
    setEndTime(end);
    setItemQry({
      beginTime: start,
      endTime: end,
    });
  };

  /**数据统计*/
  const getdatastatistics = useCallback(async () => {
    console.log('searchRef', searchRef.current);
    setChartLoading(true);
    try {
      const result = await datastatistics(clearNull(searchRef.current));
      console.log(result);
      if (result.code === 0) {
        const data: any = result.data || {};
        let {
          callNumber = [],
          connectCount = [],
          connectRate = [],
          callLossRate = [],
          totalTalkTime = [],
          aveTalkTime = [],
          userIntentionNumber = [],
          userIntentionRate = [],
        } = data;

        callNumber = callNumber.map((item: { name: string; value: number; valShow?: string }) => {
          item.name = '呼叫量';
          return item;
        });

        connectCount = connectCount.map(
          (item: { name: string; value: number; valShow?: string }) => {
            item.name = '接通数';
            return item;
          }
        );
        connectRate = connectRate.map((item: { name: string; value: number; valShow?: string }) => {
          item.name = '接通率';
          item.valShow = forMateToRato(item.value);
          return item;
        });
        callLossRate = callLossRate.map(
          (item: { name: string; value: number; valShow?: string }) => {
            item.name = '呼损率';
            item.valShow = forMateToRato(item.value);
            return item;
          }
        );
        totalTalkTime = totalTalkTime.map(
          (item: { name: string; value: number; valShow?: string }) => {
            item.name = '总通话时长';
            item.valShow = (item.value / 60 / 60).toFixed(2) + '小时';
            return item;
          }
        );
        aveTalkTime = aveTalkTime.map((item: { name: string; value: number; valShow?: string }) => {
          item.name = '平均通话时长';
          item.valShow = item.value + '秒';
          return item;
        });

        userIntentionNumber = userIntentionNumber.map(
          (item: { name: string; value: number; valShow?: string }) => {
            item.name = '意向客户数';
            return item;
          }
        );
        userIntentionRate = userIntentionRate.map(
          (item: { name: string; value: number; valShow?: string }) => {
            item.name = '意向客户比例';
            item.valShow = forMateToRato(item.value);
            return item;
          }
        );
        setChartLoading(false);
        // 只显示呼叫量和接通数
        setChartData([...callNumber, ...connectCount]);
        setCallData(data);
      }
    } catch (e) {
      setChartLoading(false);
    }
  }, []);

  /**呼叫结果统计*/
  const getcallcount = useCallback(async () => {
    try {
      const result = await callresult(clearNull(searchRef.current));
      console.log(result);
      if (result.code === 0) {
        const list: any = result.data || [];
        let sun = 0;
        for (const item of list) {
          sun += item.callValue;
        }
        setcallresultList(list);
        setcallresultTotal(sun);
      }
    } catch (e) {}
  }, []);

  // 获取话术跳出率
  const getflownodejumpout = useCallback(async () => {
    setJumpLoading(true);
    try {
      const result = await flownodejumpout(
        clearNull({
          ...searchRef.current,
          pageSize: 8,
          pageNo: currentPage,
        })
      );
      console.log(result);
      if (result.code === 0) {
        const list = result.data || [];
        setFlownodejumpoutList({ list, total: result.count || 1 });
      }
    } catch (e) {
      setFlownodejumpoutList({
        list: [],
        total: 1,
      });
    }
    setJumpLoading(false);
  }, [currentPage]);

  /**热门问题*/
  const gethotspotquestion = useCallback(async () => {
    try {
      const result = await hotspotquestion(clearNull(searchRef.current));
      console.log(result);
      if (result.code === 0) {
        const list = result.data || [];
        setHotspotquestionList(list);
      }
    } catch (e) {
      setHotspotquestionList([]);
    }
  }, []);

  const initData = useCallback(() => {
    getcallcount();
    gethotspotquestion();
    getdatastatistics();
  }, [getcallcount, getdatastatistics, gethotspotquestion]);

  useEffect(() => {
    console.log('渲染useEffect');
    initData();
  }, [initData]);

  useEffect(() => {
    getflownodejumpout();
  }, [getflownodejumpout]);
  /**
   * 重置
   */
  const resetTable = () => {
    searchRef.current = initSearchRefValue;
    sSelectRef1.current?.clear();
    sSelectRef2.current?.clear();
    setTimeType(1);
    setFlowType('');
    setTaskId('');
    setRobotId('');
    setIsZDYdate(false);
    if (currentPage !== 1) {
      setCurrentPage(1);
    } else {
      getflownodejumpout();
    }
    initData();
  };

  /**
   * 操作-搜索
   */
  const handleSearch = () => {
    if (currentPage !== 1) {
      setCurrentPage(1);
    } else {
      getflownodejumpout();
    }
    initData();
  };

  /**设置存储查询参数*/
  const setItemQry = (data: JSONObject) => {
    searchRef.current = {
      ...searchRef.current,
      ...data,
    };
  };

  /**话术跳出率的列配置*/
  const columns1 = [
    {
      title: '流程节点',
      dataIndex: 'flowNodeName',
      key: 'flowNodeName',
    },
    {
      title: '机器人',
      dataIndex: 'robotName',
      key: 'robotName',
    },
    {
      title: '跳出数',
      dataIndex: 'nodeJumpOutNumber',
      key: 'nodeJumpOutNumber',
    },
    {
      title: '跳出率',
      dataIndex: 'nodeJumpOutRate',
      key: 'nodeJumpOutRate',
      render: (text: string) => {
        return forMateToRato(Number(text));
      },
    },
  ];
  /**热门问题的列配置*/
  const columns2 = [
    {
      title: '问题',
      dataIndex: 'question',
      key: 'question',
      render: (text: string, record: any, index: number) => {
        return index + 1 + ' ' + text;
      },
    },
    {
      title: '问题数',
      dataIndex: 'questionCount',
      key: 'questionCount',
      align: 'right',
      render: (text: string) => {
        return text + '人提问';
      },
    },
  ];

  /**
   * 任务列表
   */
  const fetchTaskList = (args: FetchDataParam): FetchDataResponse => {
    return new Promise(resolve => {
      taskscanceldatapermission({
        pageNo: args.pageNum,
        pageSize: args.pageSize,
        taskName: args.keywords,
        flowType: [searchRef.current.flowType],
      })
        .then(res => {
          resolve({
            data: res.data?.map((item: any) => {
              return {
                label: item.taskName,
                value: item.taskId,
              };
            }),
            total: res.count as number,
          });
        })
        .catch(error => {
          console.error(`系统异常: ${JSON.stringify(error)}`);
        });
    });
  };
  /**
   * 机器人列表
   */
  const fetchBotList = (args: FetchDataParam): FetchDataResponse => {
    return new Promise(resolve => {
      robotscanceldatapermission({
        pageNo: args.pageNum,
        pageSize: args.pageSize,
        robotName: args.keywords,
      })
        .then(res => {
          resolve({
            data: res.data?.map((item: any) => {
              return {
                label: item.robotName,
                value: item.robotId,
              };
            }),
            total: res.count as number,
          });
        })
        .catch(error => {
          console.error(`系统异常: ${JSON.stringify(error)}`);
        });
    });
  };
  /**
   * 下载 呼叫数据统计
   */

  const downLoadFile = async () => {
    const workbook = new ExcelJS.Workbook();
    const worksheet = workbook.addWorksheet('呼叫数据统计');
    worksheet.properties.defaultRowHeight = 24;
    worksheet.properties.defaultColWidth = 24;
    //呼叫量	接通数	接通率	呼损率	总通话时长（小时)	平均通话（秒）	意向客户数	意向客户比例
    worksheet.columns = [
      { header: '呼叫量', key: 'callNumberTotal' },
      { header: '接通量', key: 'connectCountTotal' },
      { header: '接通率', key: 'connectRateTotal' },
      { header: '呼损率', key: 'callLossRateTotal' },
      { header: '总通话时长（小时)', key: 'totalTalkTimeTotal' },
      { header: '平均通话（秒）', key: 'aveTalkTimeTotal' },
      { header: '意向客户数', key: 'userIntentionNumberTotal' },
      { header: '意向客户比例', key: 'userIntentionRateTotal' },
    ];
    const {
      callNumberTotal,
      connectCountTotal,
      connectRateTotal,
      callLossRateTotal,
      totalTalkTimeTotal,
      aveTalkTimeTotal,
      userIntentionNumberTotal,
      userIntentionRateTotal,
    } = callData || {};

    worksheet.addRow({
      callNumberTotal,
      connectCountTotal,
      connectRateTotal: forMateToRato(connectRateTotal),
      callLossRateTotal: forMateToRato(callLossRateTotal),
      totalTalkTimeTotal: (totalTalkTimeTotal / 60 / 60).toFixed(2),
      aveTalkTimeTotal,
      userIntentionNumberTotal,
      userIntentionRateTotal: forMateToRato(userIntentionRateTotal),
    });

    worksheet.insertRow(1, { callNumberTotal: '日期：' + beginTime + '至' + endTime });
    worksheet.mergeCells('A1:H1');

    // 获取水印
    const base64 = setWatermark('中国电信AI主动服务平台');
    const imageId1 = workbook.addImage({ base64, extension: 'png' });
    // 添加背景图片
    worksheet.addBackgroundImage(imageId1);
    // 写入 buffer
    try {
      const buffer = await workbook.xlsx.writeBuffer();
      // 下载
      saveAs(
        new Blob([buffer], {
          type: 'application/octet-stream',
        }),
        '呼叫数据统计报表' + moment().format('YYYY年MM月DD日HH时mm分ss秒') + '.' + 'xlsx'
      );
    } catch (e) {
      console.log(e);
    }
  };
  /**
   * 绘画水印
   * @param str 要做出水印的文字
   * @returns Base64
   */
  const setWatermark = (str: string): string => {
    const id = '1.23452384164.123412416';
    if (document.getElementById(id) !== null) {
      document.body.removeChild(document.getElementById(id) as any);
    }
    // 创建一个画布
    const can = document.createElement('canvas');
    // 设置画布的长宽
    can.width = 500;
    can.height = 420;
    const cans = can.getContext('2d') as any;
    // 旋转角度
    cans.rotate((-25 * Math.PI) / 180);
    // 设置字体大小
    cans.font = '800 40px Microsoft JhengHei';
    // 设置填充绘画的颜色、渐变或者模式
    cans.fillStyle = 'rgba(130, 142, 162, 0.2)';
    // 设置文本内容的当前对齐方式
    cans.textAlign = 'center';
    // 设置在绘制文本时使用的当前文本基线
    cans.textBaseline = 'Middle';
    cans.fillText(str, 180, 350);
    const dataURL = can.toDataURL('image/png');
    return dataURL;
  };
  /**
   * 下载 话术跳出率报表
   */
  const downLoadFileForJumpout = async () => {
    const workbook = new ExcelJS.Workbook();
    const worksheet = workbook.addWorksheet('话术跳出率报表');
    worksheet.properties.defaultRowHeight = 24;
    worksheet.properties.defaultColWidth = 24;
    worksheet.columns = [
      { header: '流程节点', key: 'flowNodeName' },
      { header: '机器人', key: 'robotName' },
      { header: '跳出数', key: 'nodeJumpOutNumber' },
      { header: '跳出率', key: 'nodeJumpOutRate' },
    ];

    const { list } = flownodejumpoutList;
    for (const { flowNodeName, robotName, nodeJumpOutNumber, nodeJumpOutRate = 0 } of list) {
      worksheet.addRow({
        flowNodeName,
        robotName,
        nodeJumpOutNumber,
        nodeJumpOutRate: forMateToRato(nodeJumpOutRate),
      });
    }

    worksheet.insertRow(1, { flowNodeName: '日期：' + beginTime + '至' + endTime });
    worksheet.mergeCells('A1:D1');

    // 获取水印
    const base64 = setWatermark('中国电信AI主动服务平台');
    const imageId1 = workbook.addImage({ base64, extension: 'png' });
    // 添加背景图片
    worksheet.addBackgroundImage(imageId1);
    // 写入 buffer
    try {
      const buffer = await workbook.xlsx.writeBuffer();
      // 下载
      saveAs(
        new Blob([buffer], {
          type: 'application/octet-stream',
        }),
        '话术跳出率报表' + moment().format('YYYY年MM月DD日HH时mm分ss秒') + '.' + 'xlsx'
      );
    } catch (e) {
      console.log(e);
    }
  };

  // 渲染
  return (
    <div className="home-data-page">
      <div className="mgr-header home-list-header">
        <div className="mgr-header-left">
          <Form layout="inline" form={form}>
            <Form.Item label="任务类型">
              <Select
                style={{ width: 170 }}
                value={flowType}
                onChange={val => {
                  setFlowType(val);
                  setItemQry({ flowType: val });
                }}
              >
                <Option value="">全部</Option>
                <Option value="0">机器人任务</Option>
                <Option value="1">通知流程任务</Option>
                <Option value="2">人机协同任务</Option>
                <Option value="3">人工自动外呼任务</Option>
              </Select>
            </Form.Item>
            <Form.Item label="任务名称">
              <PageSelect
                ref={sSelectRef1}
                disabled={Boolean(robotId)}
                allowClear
                fetchData={fetchTaskList}
                placeholder="请选择任务名称"
                onChange={(val: any) => {
                  setTaskId(val);
                  setItemQry({ taskId: val, robotId: '' });
                }}
              />
            </Form.Item>
            <Form.Item label="机器人名称">
              <PageSelect
                ref={sSelectRef2}
                disabled={Boolean(taskId)}
                allowClear
                fetchData={fetchBotList}
                placeholder="请选择机器人名称"
                onChange={(val: any) => {
                  setRobotId(val);
                  setItemQry({ robotId: val, taskId: '' });
                }}
              />
            </Form.Item>
            <Form.Item>
              <Space size="middle">
                {isZDYdate && (
                  <RangePicker
                    value={
                      beginTime && endTime
                        ? [moment(beginTime, dateFormat), moment(endTime, dateFormat)]
                        : null
                    }
                    // ranges={{
                    //   今天: [moment(), moment()],
                    //   本月: [moment().startOf('month'), moment().endOf('month')],
                    // }}
                    onChange={onDateChange}
                    allowClear={false}
                  />
                )}
                {!isZDYdate && (
                  <div className="title-tab">
                    <span
                      className={timeType === 1 ? 'a1 active' : 'a1'}
                      onClick={() => handleSizeChange(1)}
                    >
                      今天
                    </span>
                    <span
                      className={timeType === 2 ? 'a2 active' : 'a2'}
                      onClick={() => handleSizeChange(2)}
                    >
                      昨天
                    </span>
                    <span
                      className={timeType === 3 ? 'a3 active' : 'a3'}
                      onClick={() => handleSizeChange(3)}
                    >
                      本周
                    </span>
                    <span
                      className={timeType === 4 ? 'a4 active' : 'a4'}
                      onClick={() => handleSizeChange(4)}
                    >
                      本月
                    </span>
                  </div>
                )}
                {isZDYdate ? (
                  <span className="zdy-date" onClick={() => setIsZDYdate(false)}>
                    固定日期
                  </span>
                ) : (
                  <span className="zdy-date" onClick={() => setIsZDYdate(true)}>
                    自定义日期
                  </span>
                )}
                <Button type="primary" onClick={handleSearch}>
                  搜索
                </Button>
                <Button type="primary" ghost onClick={resetTable}>
                  重置
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </div>
      </div>
      <div className="waihu-data">
        <div className="title-box tongji-box">
          <span className="title">数据统计</span>
          {!chartLoading && (
            <Tooltip placement="top" title="下载报表">
              <span className="down" onClick={downLoadFile}>
                <VerticalAlignBottomOutlined />
              </span>
            </Tooltip>
          )}
        </div>
        <div className="data-chart-box">
          <div className="box-1">
            <div className="item">
              <div className="title-name-box">
                <p>呼叫量</p>
                <p className="num">{callData.callNumberTotal}</p>
              </div>
              <div className="line-box">
                {/*@ts-ignore*/}
                <Line loading={chartLoading} {...callNumberConfig} />
              </div>
            </div>
            <div className="item">
              <div className="title-name-box">
                <p>接通量</p>
                <p className="num">{callData.connectCountTotal}</p>
              </div>
              <div className="line-box">
                {/*@ts-ignore*/}
                <Line loading={chartLoading} {...connectCountConfig} />
              </div>
            </div>
            <div className="item">
              <div className="title-name-box">
                <p>接通率</p>
                <p className="num">{forMateToRato(callData.connectRateTotal)}</p>
              </div>
              <div className="line-box">
                {/*@ts-ignore*/}
                <Line loading={chartLoading} {...connectRateConfig} />
              </div>
            </div>
            {hiddenItems.includes('呼损率') ? null : (
              <div className="item">
                <div className="title-name-box">
                  <p>呼损率</p>
                  <p className="num">{forMateToRato(callData.callLossRateTotal)}</p>
                </div>
                <div className="line-box">
                  <Line loading={chartLoading} {...(callLossRateConfig as any)} />
                </div>
              </div>
            )}
            <div className="item">
              <div className="title-name-box">
                <p>总通话时长</p>
                <p className="num">
                  {(callData.totalTalkTimeTotal / 60 / 60).toFixed(2)}
                  <span className="danwei">小时</span>
                </p>
              </div>
              <div className="line-box">
                {/*@ts-ignore*/}
                <Line loading={chartLoading} {...totalTalkTimeConfig} />
              </div>
            </div>
            <div className="item">
              <div className="title-name-box">
                <p>平均通话时长</p>
                <p className="num">
                  {Math.ceil(callData.aveTalkTimeTotal)} <span className="danwei">秒</span>
                </p>
              </div>
              <div className="line-box">
                {/*@ts-ignore*/}
                <Line loading={chartLoading} {...aveTalkTimeConfig} />
              </div>
            </div>
            {hiddenItems.includes('意向客户数') ? null : (
              <div className="item">
                <div className="title-name-box">
                  <p>意向客户数</p>
                  <p className="num">{callData.userIntentionNumberTotal} </p>
                </div>
                <div className="line-box">
                  <Line loading={chartLoading} {...(userIntentionNumberConfig as any)} />
                </div>
              </div>
            )}
            {hiddenItems.includes('意向客户比例') ? null : (
              <div className="item">
                <div className="title-name-box">
                  <p>意向客户比例</p>
                  <p className="num">{forMateToRato(callData.userIntentionRateTotal)}</p>
                </div>
                <div className="line-box">
                  {/*@ts-ignore*/}
                  <Line loading={chartLoading} {...userIntentionRateConfig} />
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
      <div className="waihu-data">
        <div className="title-box">
          <span className="title">呼叫结果统计</span>
        </div>
        <div className="item-box">
          {callresultList.map((item: JSONObject, index: number) => {
            if (hiddenStatus.includes(item.callStatus)) {
              return null;
            } else {
              return (
                <div className="item" key={index}>
                  <div className="name">
                    <span>{item.callValue}</span>
                    {item.callValue > 0 && callresultTotal > 0 && (
                      <span className="rat">
                        {forMateToFixed2((item.callValue / callresultTotal) * 100)}%
                      </span>
                    )}
                  </div>
                  <p>{item.callStatus}</p>
                </div>
              );
            }
          })}
        </div>
      </div>
      <section className="section-box">
        <div className="wraper chart-box">
          <div className="title">呼叫统计</div>
          <div className="chart">
            {/*@ts-ignore*/}
            <Line loading={chartLoading} {...getLineConfig} />
          </div>
        </div>
      </section>
      <div className="list-box">
        <div className="wraper new-task-box">
          <div className="title">
            <span style={{ marginRight: '5px' }}>话术跳出率</span>
            <Tooltip
              placement="rightTop"
              title="统计每个机器人流程客户挂机节点的数据，用于分析调整对应节点话术。"
            >
              <QuestionCircleFilled style={{ fontSize: 16, color: '#1890ff', cursor: 'pointer' }} />
            </Tooltip>

            {flownodejumpoutList.list.length > 0 && (
              <Tooltip placement="top" title="下载报表">
                <span className="downLoadFileForJumpout" onClick={downLoadFileForJumpout}>
                  <VerticalAlignBottomOutlined />
                </span>
              </Tooltip>
            )}
          </div>
          {flownodejumpoutList.list.length ? (
            <Table
              size="small"
              loading={jumpLoading}
              columns={columns1}
              dataSource={flownodejumpoutList.list}
              pagination={{
                hideOnSinglePage: true,
                size: 'small',
                total: flownodejumpoutList.total,
                current: currentPage,
                pageSize: 8,
                onChange: (page: any, pageSize: any) => {
                  setCurrentPage(page);
                },
              }}
              rowKey={(record, index) => `table${record.flowNodeName}${index}`}
            />
          ) : (
            <Empty description={<span>暂无数据</span>}></Empty>
          )}
        </div>
        <div className="wraper new-task-box">
          <div className="title">
            <span style={{ marginRight: '5px' }}>热门问题Top10</span>
            <Tooltip placement="rightTop" title="问题被客户多次提问，提问次数越多，排行越靠前。">
              <QuestionCircleFilled style={{ fontSize: 16, color: '#1890ff', cursor: 'pointer' }} />
            </Tooltip>
          </div>
          {hotspotquestionList.length ? (
            <Table
              columns={columns2 as any}
              showHeader={false}
              size="small"
              dataSource={hotspotquestionList}
              pagination={false}
              rowKey={(record, index) => `table${record.questionCount}${index}`}
            />
          ) : (
            <Empty description={<span>暂无数据</span>}></Empty>
          )}
        </div>
      </div>
    </div>
  );
};

export default HomePage;
